/**
 * 实时通知系统Context
 * 提供Dynamic Island通知功能
 */

import React, { createContext, useContext, useState, useCallback, useRef, useEffect } from 'react';
import { notification as antNotification } from 'antd';

// 通知类型定义
export type NotificationType = 
  | 'progress' 
  | 'status' 
  | 'info' 
  | 'warning' 
  | 'error' 
  | 'success' 
  | 'monitoring' 
  | 'sync' 
  | 'task';

export type NotificationStatus = 
  | 'idle' 
  | 'running' 
  | 'success' 
  | 'error' 
  | 'warning' 
  | 'paused' 
  | 'cancelled' 
  | 'completed' 
  | 'failed';

export type NotificationPhase = 
  | 'initial' 
  | 'transitioning' 
  | 'persistent' 
  | 'closed';

// 通知接口
export interface LiveNotification {
  id: string;
  type: NotificationType;
  status: NotificationStatus;
  title: string;
  description?: string;
  progress?: number;
  startTime: number;
  lastUpdate: number;
  endTime?: number;
  persistent?: boolean;
  autoClose?: boolean;
  data?: any;
}

// 通知状态
export interface NotificationState {
  notification: LiveNotification;
  phase: NotificationPhase;
  isVisible: boolean;
}

// Context类型
interface LiveNotificationContextType {
  notifications: NotificationState[];
  addNotification: (notification: Omit<LiveNotification, 'id' | 'startTime' | 'lastUpdate'>) => string;
  updateNotification: (id: string, updates: Partial<LiveNotification>) => void;
  removeNotification: (id: string) => void;
  clearAllNotifications: () => void;
}

// 创建Context
const LiveNotificationContext = createContext<LiveNotificationContextType | undefined>(undefined);

// Provider组件
export const LiveNotificationProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [notifications, setNotifications] = useState<NotificationState[]>([]);
  const idCounterRef = useRef(0);

  // 生成唯一ID
  const generateId = useCallback(() => {
    idCounterRef.current += 1;
    return `notification-${Date.now()}-${idCounterRef.current}`;
  }, []);

  // 添加通知
  const addNotification = useCallback((notificationData: Omit<LiveNotification, 'id' | 'startTime' | 'lastUpdate'>) => {
    const id = generateId();
    const now = Date.now();

    const newNotification: LiveNotification = {
      ...notificationData,
      id,
      startTime: now,
      lastUpdate: now,
    };

    const newState: NotificationState = {
      notification: newNotification,
      phase: 'initial',
      isVisible: true,
    };

    setNotifications(prev => [...prev, newState]);

    // 显示Ant Design通知
    const antType = newNotification.status === 'error' ? 'error' :
                   newNotification.status === 'warning' ? 'warning' :
                   newNotification.status === 'success' ? 'success' : 'info';

    antNotification[antType]({
      message: newNotification.title,
      description: newNotification.description,
      duration: newNotification.autoClose ? 4.5 : 0,
      placement: 'topRight',
    });

    return id;
  }, [generateId]);

  // 更新通知
  const updateNotification = useCallback((id: string, updates: Partial<LiveNotification>) => {
    setNotifications(prev => prev.map(state => {
      if (state.notification.id !== id) return state;

      const updatedNotification = {
        ...state.notification,
        ...updates,
        lastUpdate: Date.now(),
      };

      return {
        ...state,
        notification: updatedNotification,
      };
    }));
  }, []);

  // 移除通知
  const removeNotification = useCallback((id: string) => {
    setNotifications(prev => prev.filter(state => state.notification.id !== id));
  }, []);

  // 清空所有通知
  const clearAllNotifications = useCallback(() => {
    setNotifications([]);
  }, []);

  const contextValue: LiveNotificationContextType = {
    notifications,
    addNotification,
    updateNotification,
    removeNotification,
    clearAllNotifications,
  };

  return (
    <LiveNotificationContext.Provider value={contextValue}>
      {children}
    </LiveNotificationContext.Provider>
  );
};

// Hook
export const useLiveNotification = () => {
  const context = useContext(LiveNotificationContext);
  if (context === undefined) {
    throw new Error('useLiveNotification must be used within a LiveNotificationProvider');
  }
  return context;
};

// 导入新的通用系统
import { useProgressNotification } from '../hooks/useProgressNotification';

// 数据血缘分析专用Hook - 兼容层，使用新的通用系统
export const useDataLineageProgress = () => {
  // 使用新的通用系统
  const progressHook = useProgressNotification();

  const startLineageAnalysis = useCallback((dataSource: string) => {
    return progressHook.start({
      type: 'progress',
      title: '数据血缘解析',
      description: `正在分析 ${dataSource} 的数据血缘关系...`,
      category: 'data-lineage',
      source: dataSource,
      config: {
        persistent: true,
        autoClose: false,
        showProgress: true,
        showTimestamp: true,
        priority: 6,
      },
    });
  }, [progressHook]);

  const updateAnalysisProgress = useCallback((
    id: string,
    progress: number,
    currentStage?: string,
    currentTable?: string,
    stats?: {
      processedTables?: number;
      totalTables?: number;
      estimatedTimeRemaining?: number;
      currentOperation?: string;
    }
  ) => {
    progressHook.updateProgress(id, {
      progress,
      currentStage,
      currentItem: currentTable,
      statistics: stats,
      estimatedTime: stats?.estimatedTimeRemaining,
    });
  }, [progressHook]);

  const completeAnalysis = useCallback((
    id: string,
    success: boolean = true,
    summary?: string,
    stats?: { tables: number; relations: number; duration?: number }
  ) => {
    progressHook.complete(id, {
      success,
      summary,
      statistics: stats,
    });
  }, [progressHook]);

  const failAnalysis = useCallback((
    id: string,
    errorMessage?: string,
    errorDetails?: string
  ) => {
    progressHook.fail(id, {
      message: errorMessage || '数据血缘分析失败',
      details: errorDetails,
    });
  }, [progressHook]);

  return {
    startLineageAnalysis,
    updateAnalysisProgress,
    completeAnalysis,
    failAnalysis,
  };
};
